﻿using System;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using ComApp.Model;
using ComApp;
using ZXing.Mobile;

namespace AndroidApp
{
    [Activity(Theme = "@android:style/Theme.NoTitleBar")]
    public class ScanView : BaseActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            this.SetChildContentView(Resource.Layout.ScanView);
            AppUnity.Instance.LogService.Log("Open ScanView成功");

            var scanner = new MobileBarcodeScanner(this);
            scanner.UseCustomOverlay = true;
            var zxingOverlay = LayoutInflater.FromContext(this).Inflate(Resource.Layout.ZxingOverlay, null);
            scanner.CustomOverlay = zxingOverlay;
            var result = scanner.Scan();
            result.ContinueWith((r) => HandleScanResult(r.Result));
        }

        void HandleScanResult(ZXing.Result result)
        {
            if (result == null || string.IsNullOrEmpty(result.Text))
            {
                this.RunOnUiThread(() =>
                {
                    Toast.MakeText(this, "扫描已取消！", ToastLength.Short).Show();
                });
                return;
            }
            else
            {
                //扫描成功 偶尔扫描结果会是一串数字???
                this.RunOnUiThread(() =>
                {
                    Toast.MakeText(this, result.Text, ToastLength.Short).Show();
                });
            }
        }


        protected override bool CloseBeforeExit()
        {
            return true;
        }

        bool isFirst = true;
        protected override void OnResume()
        {
            base.OnResume();
            if (isFirst)
            {
                isFirst = false;
                AppUnity.Instance.LogService.Log("ScanView.OnResume First...");
            }
            else
            {
                AppUnity.Instance.LogService.Log("ScanView.OnResume More...");
            }
        }

    }
}

